package com.doeis.core.validator;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.regex.Matcher;

import org.apache.commons.lang3.StringUtils;

import com.doeis.tools.BeanUtils;

public class Validator {
	public static HashMap<String, String> validate(Object obj) {
		HashMap<String, String> re = new LinkedHashMap<String, String>();
		if (obj != null) {
			Class<? extends Object> clazz = obj.getClass();
			Field[] fields = clazz.getDeclaredFields();
			for (Field f : fields) {
				if (f.isAnnotationPresent(NotNull.class)) {
					validatorNotNull(obj, f, re);
				}
				if (f.isAnnotationPresent(Pattern.class)) {
					validatorPattern(obj, f, re);
				}
			}
		}
		return re;
	}

	private static void validatorNotNull(Object obj, Field f, HashMap<String, String> re) {
		Object v = BeanUtils.getProperty(obj, f.getName());
		NotNull np = (NotNull) f.getAnnotation(NotNull.class);
		if ((v == null) || ((String.class.equals(f.getType())) && (StringUtils.isBlank(v.toString())))) {
			re.put(f.getName(), np.message());
			return;
		}

		int max = np.max();
		int objLength = v.toString().length();
		if ((max < 2147483647) && (objLength > max)) {
			re.put(f.getName(), np.message());
			return;
		}

		int min = np.min();
		if ((min > -1) && (objLength < min)) {
			re.put(f.getName(), np.message());
			return;
		}
	}

	private static void validatorPattern(Object obj, Field f, HashMap<String, String> re) {
		Pattern np = (Pattern) f.getAnnotation(Pattern.class);
		String regex = np.regexp();
		if (StringUtils.isEmpty(regex)) {
			return;
		}
		Object v = BeanUtils.getProperty(obj, f.getName());
		if (v == null) {
			String msg = np.message();
			re.put(f.getName(), msg);
			return;
		}
		java.util.regex.Pattern pat = java.util.regex.Pattern.compile(regex);
		Matcher mat = pat.matcher(v.toString());
		if (!mat.find()) {
			String msg = np.message();
			re.put(f.getName(), msg);
		}
	}
}